package sz.szsmk.citizencard.mvp.presenter;

import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;

import javax.inject.Inject;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.GsdxNetApi;
import sz.szsmk.citizencard.model.network.RxSubscribers;
import sz.szsmk.citizencard.model.network.bean.request.CheckCodeRequest;
import sz.szsmk.citizencard.model.network.bean.request.CheckThirdAppReq;
import sz.szsmk.citizencard.model.network.bean.request.CheckUserRequest;
import sz.szsmk.citizencard.model.network.bean.request.GetCodeRequest;
import sz.szsmk.citizencard.model.network.bean.request.ImgCodeRequest;
import sz.szsmk.citizencard.model.network.bean.request.ProtocolsAgreeReq;
import sz.szsmk.citizencard.model.network.bean.request.RegisterRequest;
import sz.szsmk.citizencard.model.network.bean.request.ThirdAppLoginReq;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.CheckThirdAppRes;
import sz.szsmk.citizencard.model.network.bean.response.CheckUserByMobileRes;
import sz.szsmk.citizencard.model.network.bean.response.IbaseBean;
import sz.szsmk.citizencard.model.network.bean.response.ImgCodeRes;
import sz.szsmk.citizencard.model.network.bean.response.ThirdAppLoginRes;
import sz.szsmk.citizencard.model.network.bean.response.UserBean;
import sz.szsmk.citizencard.mvp.contract.ICheckCodeContact;
import sz.szsmk.citizencard.mvp.contract.IGetCodeContact;
import sz.szsmk.citizencard.mvp.contract.IMainContact;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.PubUtils;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/6/1 18:44
 * description:
 */
public class CheckCodePresenter extends IBasePresenter
        implements ICheckCodeContact.ICheckCodePresenter<ICheckCodeContact.ICheckCodeView> {

    GsdxNetApi gsdxNetApi;
    private NetworkDateSources mNetworkDateSource;

    private String androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
    private String userPhone;
    private String codeNum;

    @Inject
    public CheckCodePresenter(GsdxNetApi gsdxNetApi) {
        this.mNetworkDateSource = NetworkDateSources.getInstance();
        this.gsdxNetApi = gsdxNetApi;
    }

    @Override
    public void checkCode(final String userPhone, final String codeNum, String codeType) {
        this.userPhone = userPhone;
        this.codeNum = codeNum;
        androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        CheckUserRequest checkUserRequest = new CheckUserRequest();
        checkUserRequest.setMobile(userPhone);
        checkUserRequest.setDevice_id(androidId);
        gsdxNetApi
                .checkUser(checkUserRequest)
                .compose(mView.<IbaseBean>bindToLife())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscribers<IbaseBean>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    protected void _onNext(IbaseBean getCodeResponse) {
                        if (null != getCodeResponse) {

                            String message = getCodeResponse.getMessage();
                            String code = getCodeResponse.getCode();
                            if (null != code && code.equals("000000")) {
                                ((ICheckCodeContact.ICheckCodeView) mView).checkUserSucc(userPhone);
                            } else {
                                toRegister(userPhone, codeNum);
                            }
                        }
                        return;
                    }

                    @Override
                    protected void _onError(String message) {
                        Log.e("zdh", "请求失败" + message);
                    }
                });
    }

    @Override
    public void getImgCode(String phone) {
        ImgCodeRequest imgCodeRequest = new ImgCodeRequest();
        imgCodeRequest.setMobile(phone);

        mNetworkDateSource.getImgCode(imgCodeRequest, new SubscribeResult<ImgCodeRes>() {

            @Override
            protected void onOk(ImgCodeRes response) {
                ((ICheckCodeContact.ICheckCodeView) mView).getImgCodeSucc(response);
            }

            @Override
            protected void onFailure(ImgCodeRes res) {
                ((ICheckCodeContact.ICheckCodeView) mView).getImgCodeFail();
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                ((ICheckCodeContact.ICheckCodeView) mView).getImgCodeFail();
            }
        });
    }

    //再次获取短信验证码
    @Override
    public void getCode(String imgCode,String id, String androidId, String usePhone) {
        GetCodeRequest getCodeRequest = new GetCodeRequest();
        getCodeRequest.setDevice_id(androidId);
        getCodeRequest.setChannel_id("000001");
        getCodeRequest.setType_id(id);
        getCodeRequest.setMobile(usePhone);
        getCodeRequest.setImgCode(imgCode);
        String json = new Gson().toJson(getCodeRequest);
        L.e(Constant.TAG, "getCode:" + json);

        mNetworkDateSource.getSms(getCodeRequest, new SubscribeResult<BaseBean>() {
            @Override
            protected void onFailure(BaseBean response) {
                ((ICheckCodeContact.ICheckCodeView) mView).getSmsCodeFail(response.getMessage());
            }
            @Override
            protected void onOk(BaseBean response) {
//                PubUtils.popTipOrWarn(DaggerApplication.getIns(), response.getMessage());
                ((ICheckCodeContact.ICheckCodeView) mView).getSmsCodeSucc();
            }

            @Override
            protected void onNext(BaseBean response) {
                PubUtils.popTipOrWarn(DaggerApplication.getIns(), response.getMessage());
                ((ICheckCodeContact.ICheckCodeView) mView).getSmsCodeFail(response.getMessage());
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                Toast.makeText(DaggerApplication.getIns(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void checkMyCode(final String userPhone, final String codeNum, final String codeType) {
        CheckCodeRequest codeRequest = new CheckCodeRequest();
        codeRequest.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        codeRequest.setMobile(userPhone);
        codeRequest.setSms_code(codeNum);
//        codeRequest.setSms_code(codeNum);
        codeRequest.setSms_type(codeType);
        String json = new Gson().toJson(codeRequest);
        L.e(Constant.TAG, "checkSms===" + json);
        mNetworkDateSource.checkSms(codeRequest, new SubscribeResult<IbaseBean>() {
            @Override
            protected void onOk(IbaseBean response) {
                if (codeType.equals("1")) {
                    //toRegister(userPhone,codeNum);
                    ((ICheckCodeContact.ICheckCodeView) mView).checkMycodeSucc(userPhone,codeNum,codeType);
//                    toCheckUser(userPhone);
                } else {
                    ((ICheckCodeContact.ICheckCodeView) mView).checkMycodeSucc(response.getMessage(),codeNum,codeType);
                }
            }

            @Override
            protected void onFailure(IbaseBean response) {
                super.onFailure(response);
                if(response.getCode().equals("00003")){
                    ((ICheckCodeContact.ICheckCodeView) mView).checkMycodeFail("短信验证码错误，请重新输入验证码");
                }else{
                    ((ICheckCodeContact.ICheckCodeView) mView).checkMycodeFail(response.getMessage());
                }
            }

            @Override
            protected void onNext(IbaseBean response) {
                super.onNext(response);
                ((ICheckCodeContact.ICheckCodeView) mView).checkMycodeFail(response.getMessage());
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                ((ICheckCodeContact.ICheckCodeView) mView).checkMycodeFail(throwable.getMessage());
            }
        });
    }

    @Override
    public void checkThirdAppMobile(String userPhone, String login_type) {
        CheckThirdAppReq checkThirdAppReq = new CheckThirdAppReq();
        checkThirdAppReq.setMobile(userPhone);
        checkThirdAppReq.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        checkThirdAppReq.setLogin_type(login_type);
        String json = new Gson().toJson(checkThirdAppReq);
        L.e(Constant.TAG, "checkThirdAppReq---->" + json);
        mNetworkDateSource.checkThirdAppMobile(checkThirdAppReq, new SubscribeResult<CheckThirdAppRes>() {
            @Override
            protected void onOk(CheckThirdAppRes response) {
                String toJson = new Gson().toJson(response);
                L.e(Constant.TAG, "checkThirdAppMobile---->" + toJson);

                if (response != null) {
                    ((ICheckCodeContact.ICheckCodeView) mView).checkThirdAppMobileSucc(response);
//                    ((IGetCodeContact.IGetCodeView) mView).checkThirdAppSucc(response);
                }
            }

            @Override
            protected void onFailure(CheckThirdAppRes response) {
                super.onFailure(response);
                String toJson = new Gson().toJson(response);
                L.e(Constant.TAG, "checkThirdAppMobile---->" + toJson);
                ((ICheckCodeContact.ICheckCodeView) mView).checkThirdAppMobileFail(response);
                L.e(Constant.TAG, "checkThirdAppMobile---->" + toJson);

            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                L.e(Constant.TAG, "checkThirdAppMobile---->" + throwable.getMessage());

            }
        });


    }

    @Override
    public void loginThird(String userPhone) {
        ThirdAppLoginReq thirdAppLoginReq = new ThirdAppLoginReq();
        String login_type = ACache.get(DaggerApplication.getIns()).getAsString("login_type");
        int anInt = Integer.parseInt(login_type);
        String uid = ACache.get(DaggerApplication.getIns()).getAsString("uid");
        String androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        thirdAppLoginReq.setPassword("");
        thirdAppLoginReq.setMobile(userPhone);
        thirdAppLoginReq.setUid(uid);
        thirdAppLoginReq.setLogin_type(anInt);
        thirdAppLoginReq.setDevice_id(androidId);
        mNetworkDateSource.thirdAppLogin(thirdAppLoginReq, new SubscribeResult<ThirdAppLoginRes>() {
            @Override
            protected void onOk(ThirdAppLoginRes response) {
                String access_token = response.getAccess_token();
                String refresh_token = response.getRefresh_token();
                ACache.get(DaggerApplication.getIns()).put("access_token", access_token);
                ACache.get(DaggerApplication.getIns()).put("refresh_token", refresh_token);
                ACache.get(DaggerApplication.getIns()).remove("login_type");
                ACache.get(DaggerApplication.getIns()).remove("uid");
                ((ICheckCodeContact.ICheckCodeView) mView).loginThirdSucc();
//                ((ILoginContact.ILoginView) mView).thirdAppLoginSucc();
            }

            @Override
            protected void onFailure(ThirdAppLoginRes response) {
                super.onFailure(response);
                ((ICheckCodeContact.ICheckCodeView) mView).loginThirdFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void addUserAppAgreementRecord(String clientVersion, String operateSystem, String sceneNo,String token) {
        ProtocolsAgreeReq protocolsAgreeReq = new ProtocolsAgreeReq();
        protocolsAgreeReq.setAccess_token(token);
        protocolsAgreeReq.setClientVersion(clientVersion);
        protocolsAgreeReq.setOperateSystem(operateSystem);
        protocolsAgreeReq.setSceneNo(sceneNo);
        mNetworkDateSource.addUserAppAgreementRecord(protocolsAgreeReq, new SubscribeResult<BaseBean>() {
            @Override
            protected void onOk(BaseBean response) {
                ((IMainContact.IMainView) mView).addUserAppAgreementRecordSucc(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                ((IMainContact.IMainView) mView).addUserAppAgreementRecordFail();
            }
        });
    }

    private void toCheckUser(final String userPhone) {
        CheckUserRequest checkUserRequest = new CheckUserRequest();
        checkUserRequest.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        checkUserRequest.setMobile(userPhone);
        mNetworkDateSource.checkUserByMobile(checkUserRequest, new SubscribeResult<CheckUserByMobileRes>() {
            @Override
            protected void onOk(CheckUserByMobileRes response) {
                ((ICheckCodeContact.ICheckCodeView) mView).checkUserSucc(userPhone);
            }

            @Override
            protected void onNext(CheckUserByMobileRes response) {
                super.onNext(response);
                ((ICheckCodeContact.ICheckCodeView) mView).checkUserFail(response.getMessage());
            }

            @Override
            protected void onFailure(CheckUserByMobileRes response) {
                super.onFailure(response);
                ((ICheckCodeContact.ICheckCodeView) mView).checkUserFail(response.getMessage());
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                ((ICheckCodeContact.ICheckCodeView) mView).checkUserFail(throwable.getMessage());

            }
        });
    }

    private void toRegister(String userPhone, String codeNum) {
        RegisterRequest registerRequest = new RegisterRequest();
        registerRequest.setDevice_id(androidId);
        registerRequest.setSms_code(codeNum);
        registerRequest.setMobile(userPhone);
        mNetworkDateSource.register(registerRequest, new Action1<UserBean>() {
            @Override
            public void call(UserBean registerResponse) {
                ((ICheckCodeContact.ICheckCodeView) mView).registSuccess(registerResponse);
            }

        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                String message = throwable.getMessage();
            }
        });
    }

}
